iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 1
0
自我挑戰組

霍普菜鳥的資訊工作雜記系列 第 12

D12-透過noble藍牙掃描裝置與點燈機制

  • 分享至 

  • xImage
  •  

掃描藍芽裝置:

var fs = require("fs");
var noble = require('../node_modules/noble/index.js');


var deviceList = {};
var scanResult = {};
noble.on('discover', function (peripheral) {
    if (peripheral.advertisement.localName !== 'device_name') return;
    scanResult[peripheral.address] = deviceList[peripheral.address]||"";
});

noble.on('stateChange', function (state) {
  if (state === 'poweredOn') {
    noble.startScanning([],true);
    deviceList = JSON.parse(fs.readFileSync(__dirname+"/../data/"+"deviceList.json"));
  } else {
    noble.stopScanning();
  };

setTimeout(() => {
    noble.stopScanning();
}, 5000); 

setTimeout(() => {
    console.log(JSON.stringify(scanResult));
    process.exit(0);
}, 6000);

});

點燈機制

var noble = require('../node_modules/noble/index.js');
var get_device=false;
console.log(process.argv[2]);
noble.on('discover', function (peripheral) {
    if ((peripheral.address === process.argv[2]) && (get_device===false)) {
        console.log("device got!!");
        get_device=true;
        noble.stopScanning();
        peripheral.connect(err => {
            peripheral.discoverServices(["fff0"], (err, service) => {
                service[0].discoverCharacteristics(['fff1'], (err, char) => {
                    if (err) console.log(err); else console.log("connected!");
                    var buff = new Buffer(20);
                    buff[0] = 8;
                    char[0].write(buff);
                    console.log(`${process.argv[2]} LED ON`);
                    setTimeout(() => {
                        buff[0] = 9;
                        char[0].write(buff,true, err => {
                            console.log(`${process.argv[2]} LED OFF`);
			    setTimeout(()=>{
                          	peripheral.disconnect(()=>{
				console.log("disconnect");
			   	setTimeout(()=>{
                        	 process.exit(0);
                        	},1000);
			    });
                            },1000); 
                           });  
                    }, 2000);
                });
            });
        });
    }
});

noble.on('stateChange', function (state) {
    if (state === 'poweredOn') {
        noble.startScanning([],true);
        setTimeout(() => {
            process.exit(0);
        }, 10000);
    } else {
        noble.stopScanning();
    };
});


上一篇
D11-typescript step by step
下一篇
D13-傷兵告假一日的colorConsole
系列文
霍普菜鳥的資訊工作雜記31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言